<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div class="container">
    <h2 class="page-header">Promise封装Ajax操作</h2>
    <button class="btn btn-primary" id="btn">点击发送Ajax</button>

  </div>
  <script>
    const btn = document.querySelector('#btn');
    btn.addEventListener('click', () => {

      const p = new Promise((resolve, reject) => {
        //1.创建对象
        const xhr = new XMLHttpRequest();
        //2.初始化
        xhr.open('GET', 'https://api.apiopen.top/getJoke');
        //3.发送请求
        xhr.send();
        //4.监听状态改变
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {

              resolve(xhr.response);
            } else {
              reject(xhr.status);
            }
          }
        }
      });
      p.then(data => {
        console.log(data);
      }).catch(err => {
        console.log(err);
      });
    })
  </script>
</body>

</html>